<template>
  <div class="app-container">
    <div class="filter-container">
      <span class="filter-item">SN：</span>
      <el-input placeholder="设备SN" clearable v-model="listQuery.sn" style="width: 200px;" class="filter-item" />

      <span style="margin-left:20px;" class="filter-item">通道号：</span>
      <el-input placeholder="通道号" clearable v-model="listQuery.channel" style="width: 200px;" class="filter-item" />
      <el-date-picker class="filter-item"
        v-model="listQuery.agingDate"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        >
      </el-date-picker>

      <span style="margin-left:20px;" class="filter-item">状态：</span>
      <el-select v-model="status" placeholder="请选择" class="filter-item">
        <el-option
          v-for="item in statusList"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>

      <el-button class="filter-item search-btn" type="success" icon="el-icon-search" style="margin-left:20px;"
        @click="onSearch">
        搜索
      </el-button>

      <el-button type="success" icon="el-icon-download" class="filter-item" style="margin-left:20px;"
        @click="exportData">
        数据导出
      </el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column type="expand" fixed>
        <template slot-scope="{row}">
          <el-form label-position="left">
            <el-form-item label="设备型号">
              <span>{{ row.model }}</span>
            </el-form-item>
            <el-form-item label="开始时间">
              <span>{{ row.agingStartTime }}</span>
            </el-form-item>
            <el-form-item label="结束时间">
              <span>{{ row.agingEndTime }}</span>
            </el-form-item>
            <el-form-item label="错误代码">
              <span>{{ row.errorCode || '-'}}</span>
            </el-form-item>
            <el-form-item label="错误消息">
              <span>{{ row.agingErrorCode | getAgingError}}</span>
            </el-form-item>

            <el-form-item label="错误备注">
              <div v-for="(remark, index) in (row.agingErrorRemark || '').split('\n')" :key="index">
                {{remark}}
              </div>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column type="index" width="50" align="center"/>

      <el-table-column width="150" label="设备SN" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sn }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" label="通道码" align="center">
        <template slot-scope="{row}">
          <span>{{ row.channel }}</span>
        </template>
      </el-table-column>

      <el-table-column width="80" label="老化次数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.agingTimes }}</span>
        </template>
      </el-table-column>

      <el-table-column width="80px" label="设定电压" align="center">
        <template slot-scope="{row}">
          <span>{{ row.presetVoltage }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" label="设定电流" align="center">
        <template slot-scope="{row}">
          <span>{{ row.presetCurrent }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" label="设定时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.presetDuration ? (row.presetDuration / 3600) : '' }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="老化开始时间">
        <template slot-scope="{row}">
          <span>{{ row.agingStartTime || '-'}}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="老化结束时间">
        <template slot-scope="{row}">
          <span>{{ row.agingStopTime || '-'}}</span>
        </template>
      </el-table-column>

      <el-table-column width="130px" align="center" label="老化时长">
        <template slot-scope="{row}">
          <span v-if="row.agingStopTime && row.agingStartTime">{{ new Date(row.agingStartTime) | timeDuration(new Date(row.agingStopTime))}}</span>
          <span v-else>{{ '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="下机时间">
        <template slot-scope="{row}">
          <span>{{ row.offlineTime || '-'}}</span>
        </template>
      </el-table-column>

      <el-table-column width="120px" align="center" label="待机时长">
        <template slot-scope="{row}">
          <span v-if="row.offlineTime && row.agingStopTime">{{ new Date(row.agingStopTime) | timeDuration(new Date(row.offlineTime))}}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>

      <el-table-column width="120" label="状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.status | statusFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120" label="老化结果" align="center">
        <template slot-scope="{row}">
          <span>{{ row.agingResult == 1 ? '正常' : ( row.agingResult == 2 ? '异常' : '-') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="120px" fixed="right">
        <template slot-scope="{row}">
          <el-button type="success" size="small" icon="el-icon-data-line" @click="handleViewDetails(row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList" />

    <el-dialog
      :title="`设备运行图 SN:${viewingRow ? viewingRow.channel : ''} 通道: ${viewingRow ? viewingRow.sn : ''}`"
      :visible.sync="dialogFormVisible">
      <el-date-picker type="datetime"
                      v-model="chartDateStart"
                      :clearable="false"
                      @change="onDateChanged"
                      placeholder="选择开始时间" />

      <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
        <line-chart :chart-data="chartData" />
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="success" icon="el-icon-download" @click="exportDeviceData">
          数据导出
        </el-button>

        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDevices,
  configDevice,
  deleteDevice,
  batchAdd,
  exportDeviceData,
  exportHistoryData
} from '@/api/device'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import LineChart from './LineChart'
import { getLogs } from '@/api/device'


export default {
  name: 'Device',
  components: { Pagination, LineChart},

  filters: {
  },

  watch: {
    dialogFormVisible: function(value) {
      if (value) {
        this._getChartData()
      } else {
        this.viewingRow = null
      }
    }
  },

  data() {
    let now = new Date();
    now.setTime(now.getTime() - 7 * 24 * 3600 * 1000);
    return {
      chartDateStart: now,
      dialogFormVisible: false,
      chartData: {
        times: [],
        currents: [],
        voltages: [],
        temperatures: [],
      },
      viewingRow: null,

      status: null,
      statusList: [
        { value: 3, label: "老化完成" },
        { value: 5, label: "手动终止" },
        { value: 9, label: "老化错误" },
      ],

      devices: [],

      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        sn: null,
        agingDate: null,
        channel: null
      },
      date: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this._queryList()
    },

    _getChartData() {
      let that = this;
      let row = this.viewingRow

      if (!this.chartDateStart) {
        let yesterday = new Date();
        yesterday.setTime(yesterday.getTime() - 24 * 3600 * 1000);
        this.chartDateStart = yesterday
      }

      getLogs(row.id, this.chartDateStart).then(res => {
        let logs = res.data.data;

        that.chartData.times = logs.map(l => l.created)
        that.chartData.voltages = logs.map(l => l.voltage)
        that.chartData.currents = logs.map(l => l.current)
        that.chartData.temperatures = logs.map(l => l.temperature)
        that.chartData.device = Object.assign({}, row)
      })
    },

    handleViewDetails(row) {
      this.viewingRow = row;
      this.dialogFormVisible = true
    },

    _queryList() {
      let params = this._getQueryParams();

      this.listLoading = true
      getDevices(params).then(res => {
        this.list = res.data.data.data
        this.total = res.data.data.count
      }).finally(() => {
        this.listLoading = false
      })
    },

    _getQueryParams() {
      let agingStartTime = null
      let agingEndTime = null
      let d = this.listQuery.agingDate
      if (d && d.length > 0) {
        agingStartTime = d[0]
        agingEndTime = d[1]
      }

      return {
        page: this.listQuery.page,
        limit: this.listQuery.limit,
        sn: this.listQuery.sn,
        agingStartTime: agingStartTime,
        agingEndTime: agingEndTime,
        channel: this.listQuery.channel,
        status: this.status
      }
    },

    exportDeviceData() {
      let row = this.viewingRow

      if (!this.chartDateStart) {
        let yesterday = new Date();
        yesterday.setTime(yesterday.getTime() - 24 * 3600 * 1000);
        this.chartDateStart = yesterday
      }

      exportDeviceData(row, this.chartDateStart).then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', res.headers['content-disposition'].substring(20));
        document.body.appendChild(link);
        link.click();
      })
    },

    exportData() {
      let params = this._getQueryParams();

      exportHistoryData(params).then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', res.headers['content-disposition'].substring(20));
        document.body.appendChild(link);
        link.click();
      }).finally(() => {
      })
    },

    onSearch() {
      this._queryList()
    },

    onDelete(row) {
      this.$confirm('确认要删除？').then(() => {
        deleteDevice(row.id).then(() => {
          this.$message({
            message: '删除成功！',
            type: 'success'
          })

          this._queryList()
        });
      })
    },

    onDateChanged() {
      this._getChartData()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
